package com.googlecode.bjpodcast;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.googlecode.bjpodcast.data.PodcastDBProcess;
import com.googlecode.bjpodcast.data.PodcastDbAdapter;

public class ChannelList extends ListActivity {
	private static final String TAG = ChannelList.class.getName();
	
    private static final int ACTIVITY_ADD_CHANNEL = 0;
	private static final int ACTIVITY_VIEW_CHANNEL = 1;
    
	private static final int ADD_CHANNEL_ID = Menu.FIRST;
	private static final int EXIT_ID = Menu.FIRST + 1;
	
	private PodcastDBProcess dbProcess;
	private PodcastDbAdapter podcastDB;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Log.d(TAG, "Setting Channel List Activity");
        podcastDB = new PodcastDbAdapter(this);
        podcastDB.open();
        
        initChannelList();
    }

    
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		menu.add(getResources().getString(R.string.channellist_optionmenu_addchannel))
		.setIcon(android.R.drawable.ic_menu_add)
		.setIntent(new Intent(this, AddChannelWnd.class));
		
		menu.add(getResources().getString(R.string.channellist_optionmenu_About))
		.setIcon(android.R.drawable.ic_menu_info_details)
		.setIntent(new Intent(this, AboutWnd.class));
		
		return true;
	}
	
	 @Override
	    protected void onActivityResult(int requestCode, int resultCode, 
	                                    Intent intent) {
	        super.onActivityResult(requestCode, resultCode, intent);
	        Log.d(TAG, "Child activity ended, repopulating data");
	        initChannelList();
	    }
    
	public void initChannelList() {
		Log.d(TAG, "Filling channel list with data");
		Cursor channelListCursor = podcastDB.fetchAllChannel();
		startManagingCursor(channelListCursor);
		
		String[] from = new String[]{PodcastDbAdapter.CHANNEL_TITLE};
		int[] to = new int[]{R.id.list_channellist_row_title};
		
        SimpleCursorAdapter podcastsAdapter = new SimpleCursorAdapter(ChannelList.this, R.layout.list_channellist_row, channelListCursor, from, to);
        setListAdapter(podcastsAdapter);
		
	}
	
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	Log.d(TAG, "Opening channel at position " + position + " with id " + id);
    	Intent i = new Intent(this, ViewChannel.class);
    	i.putExtra("channelID", id);
    	startActivityForResult(i, ACTIVITY_VIEW_CHANNEL);
    }

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		podcastDB.close();
	}
	

	
    
}